package com.walkline.weather.dao;

import java.io.ByteArrayInputStream;
import java.util.Vector;

import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.walkline.util.Function;
import com.walkline.weather.WeatherException;
import com.walkline.weather.WeatherSDK;

public class YahooWeather extends YahooWeatherObject implements com.walkline.weather.inf.Weather
{
	private String _title = "";					//标题，Yahoo! Weather - Tianjin, CN
	private String _link = "";					//链接，http://us.rd.yahoo.com/dailynews/rss/weather/Tianjin__CN/*http://weather.yahoo.com/forecast/CHXX0133_c.html
	private String _language = "";				//语言，en-us
	private String _description = "";				//描述，Yahoo! Weather for Tianjin, CN
	private String _lastBuildDate = "";			//最后生成日期，Mon, 16 Jun 2014 2:59 pm CST
	private String _ttl = "";						//有效期（分钟），60
	//yweather:location								//气象预报地区
	private String _location_city = "";			//城市，Tianjin
	private String _location_region = "";			//区域，无
	private String _location_country = "";		//国家，China
	//yweather:units								//气象预报使用的单位
	private String _units_temperature = "";		//温度，C
	private String _units_distance = "";			//距离，km
	private String _units_pressure = "";			//气压，mb（百帕）
	private String _units_speed = "";				//速度，km/h
	//yweather:wind									//风
	private String _wind_chill = "";				//风寒（度），31
	private String _wind_direction = "";			//风向（度），190
	private String _wind_speed = "";				//风速，17.7
	//yweather:atmosphere
	private String _atmosphere_humidity = "";		//湿度（百分比），46
	private String _atmosphere_visibility = "";	//能见度，4.51
	private String _atmosphere_pressure = "";		//气压，982.05
	private String _atmosphere_rising = "";		//气压状态（0稳定，1上升，2下降），0
	//yweather:astronomy							//天文信息
	private String _astronomy_sunrise = "";		//日出，4:44 am
	private String _astronomy_sunset = "";		//日落，7:38 pm
	//Image
	private String _image_title = "";				//标题，Yahoo! Weather
	private String _image_link = "";				//链接，http://weather.yahoo.com
	private String _image_url = "";				//地址，http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif
	private String _image_width = "";				//宽度，142
	private String _image_height = "";			//高度，18
	//Item											//项目元素
	private String _item_title = "";				//预报标题和时间，Conditions for Tianjin, CN at 2:59 pm CST
	private String _item_link = "";				//预报链接，http://us.rd.yahoo.com/dailynews/rss/weather/Tianjin__CN/*http://weather.yahoo.com/forecast/CHXX0133_c.html
	private String _item_description = "";		//当前天气概况和明日天气预报，<![CDATA[]]> 
	private String _item_guid = "";				//唯一标识，CHXX0133_2014_06_20_7_00_CST
	//private boolean _item_guid_isPermaLink = false;	//是否永久链接，false
	private String _item_pubDate = "";			//预报发布时间，Mon, 16 Jun 2014 2:59 pm CST
	private String _item_geo_lat = "";			//地区纬度，39.13
	private String _item_geo_long = "";			//地区经度，117.19
	//yweather:condition							//当前天气预报
	private String _condition_text = "";			//文字描述，Haze
	private String _condition_code = "";			//状态代码，21
	private String _condition_temp = "";			//当前温度，31
	private String _condition_date = "";			//预报时间，Mon, 16 Jun 2014 2:59 pm CST"
	//yweather:forecast
	private Vector _forecasts = new Vector();		//未来天气预报

	public YahooWeather(WeatherSDK pWeather, StringBuffer pBuffer) throws WeatherException
	{
		super(pWeather, pBuffer);

		try {
			ByteArrayInputStream inputStream = new ByteArrayInputStream(pBuffer.toString().getBytes());
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
	        //InputStream inputStream = getClass().getResourceAsStream("/xml/forecastrss.xml");
	        Document document = builder.parse(inputStream);

	        NodeList rootNodeList = document.getElementsByTagName("channel");

	        Node node = rootNodeList.item(0);
	        NodeList nodeList = node.getChildNodes();

	        for (int i=0; i<nodeList.getLength(); i++)
	        {
	        	Node child = nodeList.item(i);
	        	if (child.getNodeType() == Node.ELEMENT_NODE)
	        	{
	        		if (child.getNodeName().equalsIgnoreCase("title")) {_title = child.getFirstChild().getNodeValue();}
	        		else if (child.getNodeName().equalsIgnoreCase("link")) {_link = child.getFirstChild().getNodeValue();}
	        		else if (child.getNodeName().equalsIgnoreCase("description")) {_description = child.getFirstChild().getNodeValue();}
	        		else if (child.getNodeName().equalsIgnoreCase("language")) {_language = child.getFirstChild().getNodeValue();}
	        		else if (child.getNodeName().equalsIgnoreCase("lastBuildDate")) {_lastBuildDate = child.getFirstChild().getNodeValue();}
	        		else if (child.getNodeName().equalsIgnoreCase("ttl")) {_ttl = child.getFirstChild().getNodeValue();}

	        		else if (child.hasAttributes())
	        		{
	        			if (child.getNodeName().equalsIgnoreCase("yweather:location"))
	        			{
	        				NamedNodeMap location = child.getAttributes();
	        				_location_city = location.getNamedItem("city").getNodeValue();
	        				_location_region = location.getNamedItem("region").getNodeValue();
	        				_location_country = location.getNamedItem("country").getNodeValue();
	        			}

	        			else if (child.getNodeName().equalsIgnoreCase("yweather:units")) {
	        				NamedNodeMap units = child.getAttributes();
	        				_units_speed = units.getNamedItem("speed").getNodeValue();
	        				_units_pressure = units.getNamedItem("pressure").getNodeValue();
	        				_units_distance = units.getNamedItem("distance").getNodeValue();
	        				_units_temperature = units.getNamedItem("temperature").getNodeValue();
	        			}

	        			else if (child.getNodeName().equalsIgnoreCase("yweather:wind")) {
	        				NamedNodeMap wind = child.getAttributes();
	        				_wind_chill = wind.getNamedItem("chill").getNodeValue();
	        				_wind_speed = wind.getNamedItem("speed").getNodeValue();
	        				_wind_direction = wind.getNamedItem("direction").getNodeValue();
	        			}

	        			else if (child.getNodeName().equalsIgnoreCase("yweather:atmosphere")) {
	        				NamedNodeMap atmosphere = child.getAttributes();
	        				_atmosphere_pressure = atmosphere.getNamedItem("pressure").getNodeValue();
	        				_atmosphere_rising = atmosphere.getNamedItem("rising").getNodeValue();
	        				_atmosphere_visibility = atmosphere.getNamedItem("visibility").getNodeValue();
	        				_atmosphere_humidity = atmosphere.getNamedItem("humidity").getNodeValue();
	        			}

	        			else if (child.getNodeName().equalsIgnoreCase("yweather:astronomy")) {
	        				NamedNodeMap astronomy = child.getAttributes();
	        				_astronomy_sunrise = astronomy.getNamedItem("sunrise").getNodeValue();
	        				_astronomy_sunset = astronomy.getNamedItem("sunset").getNodeValue();
	        			}
	        		}

	        		else if (child.getNodeName().equalsIgnoreCase("image"))
	        		{
	        			NodeList imageNodeList = child.getChildNodes();

	        			for (int j=0; j<imageNodeList.getLength(); j++)
	        			{
	        				Node image = imageNodeList.item(j);
	        				if (image.getNodeType() == Node.ELEMENT_NODE)
	        				{
	        					if (image.getNodeName().equalsIgnoreCase("title")) {_image_title = image.getFirstChild().getNodeValue();}
	        					else if (image.getNodeName().equalsIgnoreCase("link")) {_image_link = image.getFirstChild().getNodeValue();}
	        					else if (image.getNodeName().equalsIgnoreCase("url")) {_image_url = image.getFirstChild().getNodeValue();}
	        					else if (image.getNodeName().equalsIgnoreCase("width")) {_image_width = image.getFirstChild().getNodeValue();}
	        					else if (image.getNodeName().equalsIgnoreCase("height")) {_image_height = image.getFirstChild().getNodeValue();}
	        				}
	        			}
	        		}

	        		else if (child.getNodeName().equalsIgnoreCase("item"))
	        		{
	        			NodeList itemNodeList = child.getChildNodes();

	        			for (int j=0; j<itemNodeList.getLength(); j++)
	        			{
	        				Node item = itemNodeList.item(j);
	        				if (item.getNodeType() == Node.ELEMENT_NODE)
	        				{
	        					if (item.getNodeName().equalsIgnoreCase("title")) {_item_title = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("geo:lat")) {_item_geo_lat = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("geo:long")) {_item_geo_long = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("pubDate")) {_item_pubDate = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("link")) {_item_link = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("description")) {_item_description = item.getFirstChild().getNodeValue();}
	        					else if (item.getNodeName().equalsIgnoreCase("guid")) {_item_guid = item.getFirstChild().getNodeValue();}
	        				}

	        				if (item.hasAttributes())
	    	        		{
	    	        			if (item.getNodeName().equalsIgnoreCase("yweather:condition"))
	    	        			{
	    	        				NamedNodeMap condition = item.getAttributes();
	    	        				_condition_date = condition.getNamedItem("date").getNodeValue();
	    	        				_condition_temp = condition.getNamedItem("temp").getNodeValue();
	    	        				_condition_code = condition.getNamedItem("code").getNodeValue();
	    	        				_condition_text = condition.getNamedItem("text").getNodeValue();
	    	        			}

	    	        			else if (item.getNodeName().equalsIgnoreCase("yweather:forecast")) {
	    	        				NamedNodeMap forecast = item.getAttributes();
	    	        				YahooForecast yahooForecast = new YahooForecast(forecast.getNamedItem("day").getNodeValue(),
	    	        																forecast.getNamedItem("date").getNodeValue(),
	    	        																forecast.getNamedItem("low").getNodeValue(),
	    	        																forecast.getNamedItem("high").getNodeValue(),
	    	        																forecast.getNamedItem("text").getNodeValue(),
	    	        																forecast.getNamedItem("code").getNodeValue());
	    	        				_forecasts.addElement(yahooForecast);
	    	        			}
	    	        		}
	        			}
	        		}
	        	}
	        }
		} catch (Exception e) {Function.errorDialog(e.toString());}
	}

	public String getTitle() {return _title;}

	public String getLink() {return _link;}

	public String getLanguage() {return _language;}

	public String getDescription() {return _description;}

	public String getLastBuildDate() {return _lastBuildDate;}

	public String getTTL() {return _ttl;}

	public String getLocationCity() {return _location_city;}

	public String getLocationRegion() {return _location_region;}

	public String getLocationCountry() {return _location_country;}

	public String getUnitsTemperature() {return _units_temperature;}

	public String getUnitsDistance() {return _units_distance;}

	public String getUnitsPressure() {return _units_pressure;}

	public String getUnitsSpeed() {return _units_speed;}

	public String getWindChill() {return _wind_chill;}

	public String getWindDirection() {return _wind_direction;}

	public String getWindSpeed() {return _wind_speed;}

	public String getAtmosphereHumidity() {return _atmosphere_humidity;}

	public String getAtmosphereVisibility() {return _atmosphere_visibility;}

	public String getAtmospherePressure() {return _atmosphere_pressure;}

	public String getAtmosphereRising() {return _atmosphere_rising;}

	public String getAstronomySunrise() {return _astronomy_sunrise;}

	public String getAstronomySunset() {return _astronomy_sunset;}

	public String getImageTitle() {return _image_title;}

	public String getImageLink() {return _image_link;}

	public String getImageUrl() {return _image_url;}

	public String getImageWidth() {return _image_width;}

	public String getImageHeight() {return _image_height;}

	public String getItemTitle() {return _item_title;}

	public String getItemLink() {return _item_link;}

	public String getItemDescription() {return _item_description;}

	public String getItemGuid() {return _item_guid;}

	public boolean getItemGuidIsPermaLink() {return false;}

	public String getItemPubDate() {return _item_pubDate;}

	public String getItemGeoLat() {return _item_geo_lat;}

	public String getItemGeoLong() {return _item_geo_long;}

	public String getConditionText() {return _condition_text;}

	public String getConditionCode() {return _condition_code;}

	public String getConditionTemp() {return _condition_temp;}

	public String getConditionDate() {return _condition_date;}

	public Vector getForecasts() {return _forecasts;}
}